package com.crm.service.purchaseService;

import com.crm.dao.client.ClientInfoDao;
import com.crm.dao.purchaseDAO.PurchaseDAO;
import com.crm.dao.purchaseDAO.PurchaseproductiondetailDAO;
import com.crm.dao.purchaseDAO.PurchasergDAO;
import com.crm.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class PurchasergService {
    @Autowired
    private PurchasergDAO purchasergDAO;
    @Autowired
    private PurchaseDAO purchaseDAO;
    @Autowired
    private ClientInfoDao clientInfoDao;

    //添加一个采购退货明细记录
    public Purchasergdetail save(Purchasergdetail purchasergdetail){
        return purchasergDAO.save(purchasergdetail);
    }
    //查询采购退货明细的数量
    public Long queryCount(){
        return purchasergDAO.count();
    }
    //查询所有采购退货单
    public List<Purchasergdetail> allPurchasergPaged(int curPage, int pageSize){
        PageRequest page  = new PageRequest(curPage-1,pageSize);
        List<Purchasergdetail> pd  = purchasergDAO.findAllByPaged(page);
        return this.dofor(pd);
    }
    //模糊查询退货单根据供应商名称和采购标题
    public List<Purchasergdetail> getAllPurrgByMh(String q){
        return this.dofor(purchasergDAO.findAllByMh("%"+q+"%"));
    }
    //模糊查询退货单根据供应商的名称和采购标题 采购完成-未入库
    public List<Purchasergdetail> getAllPurrgByMh1(String q){
        return this.dofor(purchasergDAO.findAllByMh1("%"+q+"%"));
    }
    //模糊查询退货单根据供应商的名称和采购标题 采购完成-已入库
    public List<Purchasergdetail> getAllPurrgByMh2(String q){
        return this.dofor(purchasergDAO.findAllByMh2("%"+q+"%"));
    }
    //遍历赋值
    public List<Purchasergdetail> dofor(List<Purchasergdetail> plist){
        for (Purchasergdetail p:plist) {
            if(p.getPuridfk()!=null){
                if(purchaseDAO.findOne(p.getPuridfk())!=null){
                    Purchase purchase = purchaseDAO.findOne(p.getPuridfk());
                    p.setPurtheme(purchase.getPurtheme());
                    p.setPurstatus(purchase.getPurstatus());
                    p.setClientname(clientInfoDao.findOne(purchase.getClientId()).getCname());
                }
            }
        }
        return plist;
    }
    public List<Inandoutlog> findAllBymh(){
        List<Inandoutlog> list = new ArrayList<>();
        List<Purchasergdetail> purchasergdetails = purchasergDAO.findAllBymh();
        for (Purchasergdetail p:purchasergdetails) {
            Inandoutlog io =new Inandoutlog();
            io.setIoDispatherId(p.getPrgid());
            io.setIoDispatherTitle(p.getPrgtheme());
            list.add(io);
        }
        return list;
    }
    public Purchasergdetail findOneById(Long pdid){
        return purchasergDAO.findOne(pdid);
    }
}
